//
//  ViewController.m
//  FMDB-Practice1
//
//  Created by lanou3g on 16/1/21.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "ViewController.h"
#import "FMDatabase.h"
#import "FMDB/FMDatabaseQueue.h"


@interface ViewController ()



@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingString:@"/user.sqlite"];
    
    FMDatabase * DB = [FMDatabase databaseWithPath:filePath];
    
    //打开
//    if ([DB open]) {
//        NSLog(@"can open!");
//    }
 
    if (![DB open]) {
        return;//如果数据库没有打开就不继续执行了
    }
    
    
    
    
    
    
    //增删改查
    if ([DB executeUpdate:@"create table if not exists user(number integer primary key autoincrement,name text not null,age integer );"]) {
        
        NSLog(@"success T");
        
    }else{
        
        NSLog(@"false T");
    }
    
    
    //添加数据
    if ([DB executeUpdate:@"insert into user (name,age) values(?,?)",@"haha",@18]) {
        
        NSLog(@"add ");
        
    }else{
        
        NSLog(@"cannot add");
    }
    
    
    //更新数据(从1开始不从0 开始)
    if ([DB executeUpdate:@"update user set name = ? where number = ?",@"hehe",@1]) {
        
        NSLog(@"change ");
        
        
    }else{
        
        NSLog(@"cannot change");
    }
    
    
    //查找
    FMResultSet * set = [DB executeQuery:@"select *from  user"];
    
    //[set next]穷举
    while ([set next]) {
        NSInteger number = [set longForColumn:@"number"];
//        int number = [set intForColumn:@"number"];
        NSString * name = [set stringForColumn:@"name"];
        NSInteger age = [set longForColumn:@"age"];
//        int age = [set intForColumn:@"age"];
        
        NSLog(@"%ld %@ %ld",number,name,age);
        
    }
    
    
    //删除
    if ([DB executeUpdate:@"delete from user where number = ?",@2]) {
        
        NSLog(@"delete!");
        
        
    }else{
        
        NSLog(@"cannot delete");
    }
    
    
    
    //关闭
    if ([DB close]) {
        NSLog(@"close");
    }
    
    //多线程
    FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:filePath];
    [queue inDatabase:^(FMDatabase *db) {
       
        [db executeUpdate:@"insert into user (name ,age) values (?,?)",@"he",@4];
        FMResultSet * rs = [db executeQuery:@"select * from user"];
        while ([rs next]) {
            NSLog(@"%@ %d",[rs stringForColumn:@"name"],[rs intForColumn:@"age"]);
        }
        
    }];
    
    
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
